package com.xd.core.business.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.base.CustomRowHeightColWidthHandler;
import com.xd.common.base.RowHeightColWidthModel;
import com.xd.common.constant.SysConstant;
import com.xd.common.properties.PassWordKeyProperties;
import com.xd.common.util.AESUtil;
import com.xd.common.util.SecurityUtil;
import com.xd.core.business.dto.MortgageQuery;
import com.xd.core.business.entity.Mortgage;
import com.xd.core.business.mapper.CertificationMapper;
import com.xd.core.business.mapper.MortgageMapper;
import com.xd.core.business.service.IMortgageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xd.core.business.vo.IncomingInfoMortgageVo;
import com.xd.core.business.vo.IncomingInfoMortgageVo1;
import com.xd.core.business.vo.IncomingInfoPageVo;
import com.xd.core.business.vo.MortgagePageVo;
import com.xd.core.company.dto.HomeQueryDto;
import com.xd.core.company.vo.CertificationAndMortgage;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 抵押表 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-02-26
 */
@Service
public class MortgageServiceImpl extends ServiceImpl<MortgageMapper, Mortgage> implements IMortgageService {

    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.exportFile}")
    private String exportFile;
    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private MortgageMapper mortgageMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Autowired
    private PassWordKeyProperties passWordKeyProperties;
    @Autowired
    private CertificationMapper certificationMapper;

    @Override
    public Page<MortgagePageVo> getMortgageList(MortgageQuery query) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = query.getCompanyId();
        List<Integer> userIds = null;
        if (!companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE) && !companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)) {//不是平台和集团
            companyId = SecurityUtil.getLoginCompanyId();
            userIds = iSysUserService.getUserIdsByGroup();
        }
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return (Page<MortgagePageVo>) mortgageMapper.getMortgageList(query,userIds,companyId,companyType);
    }

    @Override
    public IncomingInfoMortgageVo getDetail(Integer id) {
        return mortgageMapper.getDetail(id);
    }

    @Override
    public IncomingInfoMortgageVo1 getDetail1(Integer id) {
        return mortgageMapper.getDetail1(id);
    }

    @Override
    public void exportIncomingInfoList(MortgageQuery query, Integer id) {
        String name = "抵押excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 8, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 9, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 10, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 11, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 12, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 13, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 14, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);

            ExcelWriter write = EasyExcel.write(fileOutputStream, MortgagePageVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            query.setPageSize(0);
            List<MortgagePageVo> list = getMortgageList(query);
            for (MortgagePageVo customerInfoVo : list) {
                String decryptPhone = AESUtil.decrypt(customerInfoVo.getPhone(), aesKey);
                customerInfoVo.setPhone(decryptPhone);
            }
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public CertificationAndMortgage getCertificationAndMortgage(HomeQueryDto query) {
        String companyType = SecurityUtil.getLoginCompany().getCompanyType();
        Integer companyId = SecurityUtil.getLoginCompanyId();
        if (StringUtils.isEmpty(query.getStartTime()) && StringUtils.isEmpty(query.getEndTime())) {
            LocalDate today = LocalDate.now();
            LocalDate oneMonthAgo = today.minusMonths(1);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            query.setStartTime(oneMonthAgo.format(formatter));
            query.setEndTime(today.format(formatter));

        }
        Integer mortgageCounts = mortgageMapper.selectCounts(query,companyId,companyType);
        Integer certificationCounts = certificationMapper.selectCounts(query,companyId,companyType);
        CertificationAndMortgage certificationAndMortgage = new CertificationAndMortgage();
        certificationAndMortgage.setMortgageCounts(mortgageCounts);
        certificationAndMortgage.setCertificationCounts(certificationCounts);
        return certificationAndMortgage;
    }
}

